package de.justphil.tcg.tcgclient;

import java.util.concurrent.TimeUnit;

import javax.swing.JScrollBar;

import org.glassfish.grizzly.websockets.DataFrame;
import org.glassfish.grizzly.websockets.WebSocketClient;
import org.glassfish.grizzly.websockets.WebSocketEngine;

/**
 * Chat websocket client connection. This {@link MyWebSocketClient} customizes default {@link WebSocket} with {@link
 * ChatWebSocket}, which includes some chat specific properties and logic.
 *
 * @author Alexey Stashok
 */
public class MyWebSocketClient extends WebSocketClient {
	
	private final TCGClient c;
	private HeartBeatingWebSocket heartBeatingWebSocket;

    /**
     * Construct a client {@link MyWebSocketClient}
     *
     * @param login user name
     */
    public MyWebSocketClient(String uri, TCGClient c) {
    	super(uri, WebSocketEngine.DEFAULT_VERSION);
    	this.c = c;
    	this.heartBeatingWebSocket = null;
    }

    /**
     * The method is called, when client-side {@link ChatWebSocket} gets connected. At this stage we need to send login
     * frame to the server.
     */
    @Override
    public void onConnect() {
    	super.onConnect();
    	c.getConnectButton().setText(TCGClient.DISCONNECT);
    	c.getConnectedLabel().setText(TCGClient.CONNECTED);
    	c.getOutputTextArea().setText("");
    	c.getOutputTextArea().append("Connected to " + c.getUriTextField().getText() + "\n");
    	
    	heartBeatingWebSocket = new HeartBeatingWebSocket(this, 2, TimeUnit.SECONDS);
    	heartBeatingWebSocket.start();
    }

    /**
     * Method is called, when {@link ChatWebSocket} receives a message.
     */
    @Override
    public void onMessage(String msg) {
    	// Determine whether the scrollbar is currently at the very bottom position.
    	JScrollBar vbar = c.getOutputScrollPane().getVerticalScrollBar();
    	boolean autoScroll = ((vbar.getValue() + vbar.getVisibleAmount()) == vbar.getMaximum());

    	c.getOutputTextArea().append(msg + "\n");

    	// now scroll if we were already at the bottom.
    	if( autoScroll ) c.getOutputTextArea().setCaretPosition( c.getOutputTextArea().getDocument().getLength() );
    }

    @Override
    public void onClose(DataFrame frame) {
    	if (heartBeatingWebSocket != null) {
    		heartBeatingWebSocket.stopHeartBeating();
    		heartBeatingWebSocket = null;
    	}
    	
    	c.getConnectButton().setText(TCGClient.CONNECT);
    	c.getConnectedLabel().setText(TCGClient.NOT_CONNECTED);
    }
    
    public void sendMessage(String msg) {
    	if (heartBeatingWebSocket != null)
    		heartBeatingWebSocket.send(msg);
    }

    /*
    public static void main(String[] args) throws Exception {
        // initialize transport
        ChatClient websocket = null;
        try {
            // initialize console reader
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Type 'q' and <enter> any time to exit");
            String login;
            // Ask for the user name
            do {
                System.out.print("Login: ");
                login = reader.readLine();
                if (login == null || "q".equals(login)) {
                    return;
                }
                login = login.trim();
            } while (login.isEmpty());
            // Initialize websocket connect and login to chat
            final String uri = "ws://localhost:8888/grizzly-websockets-chat/chat";
            final ChatClient client = new ChatClient(uri, login);
            websocket = (ChatClient) client.connect();
            // websocket client working cycle... Type the message and send it to the server
            String message;
            do {
                System.out.print("Message ('q' to quit) >");
                message = reader.readLine();
                if (!websocket.isConnected() ||
                    message == null || "q".equals(message)) {
                    return;
                }
                message = message.trim();
                // if message is not empty - send it to the server
                if (message.length() > 0) {
                    websocket.send(message);
                }
            } while (true);

        } finally {
            // close the websocket
            if (websocket != null) {
                websocket.close();
            }
        }
    }
    */
}